package com.jrtc.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jrtc.base.config.constants.PublicConstants;
import com.jrtc.base.config.dto.ResultDTOBuilder;
import com.jrtc.base.entity.bo.*;
import com.jrtc.base.entity.vo.*;
import com.jrtc.dao.*;
import com.jrtc.service.DoctorService;
import com.jrtc.service.HealthplanService;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 康复计划表(Healthplan)表服务实现类
 *
 * @author makejava
 * @since 2022-03-21 17:34:12
 */
@Service("healthplanService")
public class HealthplanServiceImpl implements HealthplanService
{
    @Resource
    private HealthplanDao healthplanDao;
    @Resource
    private ExerciseprescriptionDao exerciseprescriptionDao;
    @Resource
    private DoctorDao doctorDao;
    @Resource
    private PatientExerciseprescriptionDao patientExerciseprescriptionDao;
    @Resource
    private SysDictItemDao sysDictItemDao;
    @Resource
    private SysDictDao sysDictDao;
    @Resource
    private PrescriptionVideoDao prescriptionVideoDao;
    @Resource
    private PublicVideoDao publicVideoDao;
    @Resource
    private DoctorService doctorService;
    @Resource
    private RoleDao roleDao;
    @Resource
    private HospitalDao hospitalDao;
    @Resource
    private DiseaseDao diseaseDao;
    @Resource
    private PrescriptionLabelOneDao prescriptionLabelOneDao;
    @Resource
    private PrescriptionLabelTwoDao prescriptionLabelTwoDao;
    @Resource
    private PrescriptionLabelThreeDao prescriptionLabelThreeDao;

    /**
     * 通过ID查询单条数据
     *
     * @param healthplanId 主键
     * @return 实例对象
     */
    @Override
    public Healthplan queryById(Integer healthplanId) {
        return this.healthplanDao.queryById(healthplanId);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit 查询条数
     * @return 对象列表
     */
    @Override
    public List<Healthplan> queryAllByLimit(int offset, int limit) {
        return this.healthplanDao.queryAllByLimit(offset, limit);
    }

    @Override
    public IPage<Healthplan> queryHealthplanList(Healthplan healthplan)
    {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<Healthplan> page = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(healthplan.getPageNo(), healthplan.getPageSize());
        IPage<Healthplan> healthplanPage = this.healthplanDao.queryHealthplanList(page, healthplan);
        return healthplanPage;
    }
    /**
     * 新增数据
     *
     * @param healthplan 实例对象
     * @return 实例对象
     */
    @Override
    public Healthplan insert(Healthplan healthplan) {
        this.healthplanDao.insert(healthplan);
        return healthplan;
    }

    /**
     * 修改数据
     *
     * @param healthplan 实例对象
     * @return 实例对象
     */
    @Override
    public Healthplan update(Healthplan healthplan) {
        this.healthplanDao.update(healthplan);
        return this.queryById(healthplan.getHealthplanId());
    }

    /**
     * 通过主键删除数据
     *
     * @param healthplanId 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer healthplanId) {
        return this.healthplanDao.deleteById(healthplanId) > 0;
    }

    /**
     * 查询指定康复计划
     * */
    @Override
    public HealthplanVo selectHealthplan(Integer healthplanId) throws Exception {
        if (healthplanId != null && healthplanId != 0){
            PatientExerciseprescription patientExerciseprescription = patientExerciseprescriptionDao.queryById(healthplanId);
            HealthplanVo healthplanVo = new HealthplanVo();
            healthplanVo.setHealthplanId(patientExerciseprescription.getFavouriteId());
            healthplanVo.setHealthplanName(patientExerciseprescription.getPrescriptionName());

            Healthplan healthplan = healthplanDao.selectHealthplan(healthplanId);

            int days = (int) ((healthplan.getHealthplanEndtime().getTime() - healthplan.getHealthplanStarttime().getTime()) / (1000*3600*24)) / 7;

            if (days == 0){
                days = 1;
            }
            healthplanVo.setLastsAFewWeeks(days);
            if (healthplan.getHealthplanWeekday() != null && !healthplan.getHealthplanWeekday().equals("")){
                List<String> list = Arrays.asList(healthplan.getHealthplanWeekday().split(","));
                healthplanVo.setDaysAWeek(list.size());
            }
            else {
                throw new Exception("未获取到数据");
            }

            Exerciseprescription exerciseprescription = exerciseprescriptionDao.selectExerciseprescriptionById(patientExerciseprescription.getPrescriptionId());

            healthplanVo.setSportClass(exerciseprescription.getExerciseLevel());
            healthplanVo.setSeveralSetsOfActions(exerciseprescription.getExerciseEveryrepeat());

            Doctor doctor = doctorDao.selectDoctorById(healthplan.getDoctorId());
            healthplanVo.setDoctorName(doctor.getDoctorName());
            healthplanVo.setProfessional(doctor.getProfessional());
            return healthplanVo;
        }
        else {
            throw new Exception("缺少必要参数");
        }
    }

    /**
     * 运动处方模板列表
     * */
    @Override
    public List<Healthplan> healthPlanList() {
        List<Healthplan> healthplanList = healthplanDao.healthPlanList();
        return healthplanList;
    }

    /**
     * id获取运动处方模板信息
     * */
    @Override
    public Healthplan healthPlanById(Integer id) {
        Healthplan healthplan = healthplanDao.selectHealthplan(id);
        List<PrescriptionVideo> prescriptionVideos = prescriptionVideoDao.prescriptionVideos(healthplan.getHealthplanId());
        if (prescriptionVideos.size() > 0)
            healthplan.getPublicVideoList().addAll(prescriptionVideos);

        if (healthplan != null && healthplan.getDictItemId() != null && healthplan.getDictItemId() != 0){
            SysDictItem sysDictItem = sysDictItemDao.queryById(healthplan.getDictItemId());
            if (sysDictItem != null){
                healthplan.setSmallClassification(sysDictItem.getItemName());

                SysDict sysDict = sysDictDao.queryById(sysDictItem.getDictId());
                if (sysDict != null){
                    healthplan.setMainCategory(sysDict.getDictName());
                }
            }
        }
        return healthplan;
    }

    /**
     * 定制运动处方模板
     * */
    @Override
    public int customMade(Healthplan healthplan, HttpServletRequest request) throws Exception {
        Doctor loginDoctor;
        try {
            loginDoctor = doctorService.getLoginDoctor(request);
        } catch (Exception e){
            throw new Exception(e.getMessage());
        }

        if (loginDoctor == null){
            throw new Exception("登录已过期");
        }

        healthplan.setDoctorId(loginDoctor.getDoctorId());

        if (loginDoctor.getHospitalCode() != null){
            Hospital hospital = hospitalDao.hospitalByNum(loginDoctor.getHospitalCode());
            if (hospital != null){
                healthplan.setHospitalId(hospital.getId());
            }
        }

        Role role = roleDao.queryById(loginDoctor.getRoleId());
        if (role != null){
            if (role.getRoleName().equals(PublicConstants.RoleEnum.SuperAdmin.getValue())){
                healthplan.setClassification("common");
            }
            else {
                healthplan.setClassification("own");
            }
        }

        int insert = healthplanDao.insert(healthplan);
        if (healthplan.getPurposeList() != null){
            int i = insertPrescriptionLabelOne(healthplan.getPurposeList(), healthplan.getHealthplanId());
            if (i <= 0){
                throw new Exception("添加目的标签失败");
            }
        }

        if (healthplan.getRiskLevelList() != null){
            int i = insertPrescriptionLabelOne(healthplan.getRiskLevelList(), healthplan.getHealthplanId());
            if (i <= 0){
                throw new Exception("添加风险等级标签失败");
            }
        }

        if (healthplan.getComplicationList() != null){
            int i = insertPrescriptionLabelOne(healthplan.getComplicationList(), healthplan.getHealthplanId());
            if (i <= 0){
                throw new Exception("添加并发症标签失败");
            }
        }

        if (healthplan.getMuscleSelectionList() != null){
            int i = insertPrescriptionLabelOne(healthplan.getMuscleSelectionList(), healthplan.getHealthplanId());
            if (i <= 0){
                throw new Exception("添加肌肉选择标签失败");
            }
        }

        if (healthplan.getApplicableDiseaseList() != null){
            int i = insertPrescriptionLabelOne(healthplan.getApplicableDiseaseList(), healthplan.getHealthplanId());
            if (i <= 0){
                throw new Exception("添加适用症标签失败");
            }
        }

        if (healthplan.getPublicVideoList() != null && healthplan.getPublicVideoList().size() > 0){
            for (PrescriptionVideo prescriptionVideo : healthplan.getPublicVideoList()) {
                PublicVideo publicVideo = publicVideoDao.selectPublicVideo(prescriptionVideo.getPublicVideoId());

                if (publicVideo != null){
                    prescriptionVideo.setPublicVideoName(publicVideo.getPrescriptionVideoName());
                    prescriptionVideo.setPublicVideoUrl(publicVideo.getPrescriptionVideoUrl());
                    prescriptionVideo.setTime(publicVideo.getTime());
                    prescriptionVideo.setBranch(publicVideo.getBranch());
                    prescriptionVideo.setSecond(publicVideo.getSecond());
                }

                prescriptionVideo.setHealthplanId(healthplan.getHealthplanId());
                prescriptionVideo.setClassification("template");
                insert = prescriptionVideoDao.insert(prescriptionVideo);
                if (insert <= 0){
                    throw new Exception("添加模板视频失败:" + prescriptionVideo.getPublicVideoId());
                }
            }
        }
        return insert;
    }

    /**
     * 查询待修改的运功处方模板
     * */
    @Override
    public Healthplan selectCustomMade(Integer id) {
        Healthplan healthplan = healthplanDao.queryById(id);

        List<PrescriptionLabelOne> prescriptionLabelOnes = prescriptionLabelOneDao.prescriptionLabelOne(healthplan.getHealthplanId());
        if (prescriptionLabelOnes != null && prescriptionLabelOnes.size() > 0){
            for (PrescriptionLabelOne prescriptionLabelOne : prescriptionLabelOnes) {
                List<PrescriptionLabelTwo> prescriptionLabelTwos = prescriptionLabelTwoDao.prescriptionLabelTwo(prescriptionLabelOne.getId());
                if (prescriptionLabelTwos != null && prescriptionLabelTwos.size() > 0){
                    for (PrescriptionLabelTwo prescriptionLabelTwo : prescriptionLabelTwos) {
                        List<PrescriptionLabelThree> prescriptionLabelThrees = prescriptionLabelThreeDao.prescriptionLabelThree(prescriptionLabelTwo.getId());
                        if (prescriptionLabelThrees != null && prescriptionLabelThrees.size() > 0){
                            prescriptionLabelTwo.setLabelThrees(prescriptionLabelThrees);
                        }
                    }
                    prescriptionLabelOne.setLabelTwos(prescriptionLabelTwos);
                }
                if (prescriptionLabelOne.getName().equals("目的")){
                    healthplan.setPurposeList(prescriptionLabelOne);
                }
                else if (prescriptionLabelOne.getName().equals("风险等级")){
                    healthplan.setRiskLevelList(prescriptionLabelOne);
                }
                else if (prescriptionLabelOne.getName().equals("并发症")){
                    healthplan.setComplicationList(prescriptionLabelOne);
                }
                else if (prescriptionLabelOne.getName().equals("肌肉选择")){
                    healthplan.setMuscleSelectionList(prescriptionLabelOne);
                }
                else if (prescriptionLabelOne.getName().equals("适用症")){
                    healthplan.setApplicableDiseaseList(prescriptionLabelOne);
                }
            }
        }

        List<PrescriptionVideo> prescriptionVideos = prescriptionVideoDao.prescriptionVideos(healthplan.getHealthplanId());
        healthplan.setPublicVideoList(prescriptionVideos);

        SysDictItem sysDictItem = sysDictItemDao.queryById(healthplan.getDictItemId());
        if (sysDictItem != null){
            healthplan.setCategory(sysDictItem.getItemName());
            healthplan.setDictItemId(sysDictItem.getId());
        }

        SysDict sysDict = sysDictDao.queryById(sysDictItem.getDictId());
        if (sysDict != null){
            healthplan.setParentCategory(sysDict.getDictName());
            healthplan.setMainCategoryId(sysDict.getId());
        }
        return healthplan;
    }

    /**
     * 修改运动处方模板
     * */
    @Override
    public int saveCustomMade(Healthplan healthplan) throws Exception {
        int insert = healthplanDao.update(healthplan);

        if (healthplan.getPurposeList() != null){
            int i = insertPrescriptionLabelOne(healthplan.getPurposeList(), healthplan.getHealthplanId());
            if (i <= 0){
                throw new Exception("添加目的标签失败");
            }
        }

        if (healthplan.getRiskLevelList() != null){
            int i = insertPrescriptionLabelOne(healthplan.getRiskLevelList(), healthplan.getHealthplanId());
            if (i <= 0){
                throw new Exception("添加风险等级标签失败");
            }
        }

        if (healthplan.getComplicationList() != null){
            int i = insertPrescriptionLabelOne(healthplan.getComplicationList(), healthplan.getHealthplanId());
            if (i <= 0){
                throw new Exception("添加并发症标签失败");
            }
        }

        if (healthplan.getMuscleSelectionList() != null){
            int i = insertPrescriptionLabelOne(healthplan.getMuscleSelectionList(), healthplan.getHealthplanId());
            if (i <= 0){
                throw new Exception("添加肌肉选择标签失败");
            }
        }

        if (healthplan.getApplicableDiseaseList() != null){
            int i = insertPrescriptionLabelOne(healthplan.getApplicableDiseaseList(), healthplan.getHealthplanId());
            if (i <= 0){
                throw new Exception("添加适用症标签失败");
            }
        }

        List<PrescriptionVideo> prescriptionVideos = prescriptionVideoDao.prescriptionVideos(healthplan.getHealthplanId());
        if (prescriptionVideos != null && prescriptionVideos.size() > 0) {
            for (PrescriptionVideo prescriptionVideo : prescriptionVideos) {
                prescriptionVideoDao.deleteById(prescriptionVideo.getId());
            }
        }
        if (healthplan.getPublicVideoList() != null && healthplan.getPublicVideoList().size() > 0) {
            for (PrescriptionVideo prescriptionVideo : healthplan.getPublicVideoList()) {
                PublicVideo publicVideo = publicVideoDao.selectPublicVideo(prescriptionVideo.getPublicVideoId());

                if (publicVideo != null) {
                    prescriptionVideo.setPublicVideoName(publicVideo.getPrescriptionVideoName());
                    prescriptionVideo.setPublicVideoUrl(publicVideo.getPrescriptionVideoUrl());
                    prescriptionVideo.setTime(publicVideo.getTime());
                    prescriptionVideo.setBranch(publicVideo.getBranch());
                    prescriptionVideo.setSecond(publicVideo.getSecond());
                }

                prescriptionVideo.setHealthplanId(healthplan.getHealthplanId());
                prescriptionVideo.setClassification("template");
                insert = prescriptionVideoDao.insert(prescriptionVideo);
                if (insert <= 0) {
                    throw new Exception("修改模板视频失败:" + prescriptionVideo.getPublicVideoId());
                }
            }
        }
        return insert;
    }

    /**
     * 运动处方模板列表
     * */
    @Override
    public TmpCustomMadeVo customMades(HttpServletRequest request, CustomMade customMade) throws Exception {
        Doctor loginDoctor;
        try {
            loginDoctor = doctorService.getLoginDoctor(request);
        } catch (Exception e){
            throw new Exception(e.getMessage());
        }

        if (loginDoctor == null){
            throw new Exception("登录已过期");
        }

        TmpCustomMadeVo tmpCustomMadeVo = new TmpCustomMadeVo();

        List<CustomMades> customMades = new ArrayList<>();

        Role role = roleDao.queryById(loginDoctor.getRoleId());

        List<SysDictItem> sysDictItemList = new ArrayList<>();
        if (customMade!= null && customMade.getId() != null && customMade.getId().size() > 0){
            for (Integer integer : customMade.getId()) {
                SysDictItem sysDictItem = sysDictItemDao.queryById(integer);
                if (sysDictItem != null){
                    sysDictItemList.add(sysDictItem);
                }
            }
        }
        else {
            sysDictItemList = sysDictItemDao.sysDictItemList();
        }

        Integer own = 0;
        Integer count = 0;
        if(!role.getRoleName().equals(PublicConstants.RoleEnum.SuperAdmin.getValue())){
            for (SysDictItem sysDictItem : sysDictItemList) {
                CustomMades tmpCustomMades = new CustomMades();

                Hospital hospital = hospitalDao.hospitalByNum(Integer.parseInt(loginDoctor.getAffiliatedHospital()));

                List<Healthplan> healthplans = healthplanDao.healthplans(customMade.getName(), sysDictItem.getId(), hospital.getId());
                if (healthplans != null && healthplans.size() > 0){
                    tmpCustomMades.setId(sysDictItem.getId());
                    tmpCustomMades.setCount(healthplans.size());
                    tmpCustomMades.setName(sysDictItem.getItemName());
                    own = own + healthplans.size();
                    List<CustomMadesVo> customMadesVoList = new ArrayList<>();
                    for (Healthplan healthplan : healthplans) {
                        CustomMadesVo customMadesVo = new CustomMadesVo();
                        customMadesVo.setId(healthplan.getHealthplanId());
                        customMadesVo.setName(healthplan.getHealthplanName());
                        customMadesVo.setUrl(healthplan.getExercisePictureURL());
                        customMadesVo.setExerciseLevel(healthplan.getExerciseLevel());
                        customMadesVoList.add(customMadesVo);
                    }
                    tmpCustomMades.setOwnList(customMadesVoList);
                    customMades.add(tmpCustomMades);
                }
            }
        }

        for (SysDictItem sysDictItem : sysDictItemList) {
            CustomMades tmpCustomMades = new CustomMades();
            List<Healthplan> healthplans = healthplanDao.healthplans(customMade.getName(), sysDictItem.getId(), 0);
            if (healthplans != null && healthplans.size() > 0){
                tmpCustomMades.setId(sysDictItem.getId());
                tmpCustomMades.setCount(healthplans.size());
                tmpCustomMades.setName(sysDictItem.getItemName());
                count = count + healthplans.size();
                List<CustomMadesVo> customMadesVoList = new ArrayList<>();
                for (Healthplan healthplan : healthplans) {
                    CustomMadesVo customMadesVo = new CustomMadesVo();
                    customMadesVo.setId(healthplan.getHealthplanId());
                    customMadesVo.setName(healthplan.getHealthplanName());
                    customMadesVo.setUrl(healthplan.getExercisePictureURL());
                    customMadesVo.setExerciseLevel(healthplan.getExerciseLevel());
                    customMadesVoList.add(customMadesVo);
                }
                tmpCustomMades.setCustomMadesVoList(customMadesVoList);
                customMades.add(tmpCustomMades);
            }
        }

        tmpCustomMadeVo.setOwn(own);
        tmpCustomMadeVo.setCount(count);
        tmpCustomMadeVo.setCustomMadesList(customMades);

        return tmpCustomMadeVo;
    }

    /**
     * 添加标签
     * */
    public int insertPrescriptionLabelOne(PrescriptionLabelOne purpose, Integer id) throws Exception {
        purpose.setExercisePrescriptionId(id);
        int insert = prescriptionLabelOneDao.insert(purpose);
        if (insert <= 0){
            throw new Exception("添加第一层失败");
        }

        if (purpose.getLabelTwos() != null && purpose.getLabelTwos().size() > 0){
            for (PrescriptionLabelTwo labelTwo : purpose.getLabelTwos()) {
                labelTwo.setLabelOneId(purpose.getId());
                insert = prescriptionLabelTwoDao.insert(labelTwo);
                if (insert <= 0){
                    throw new Exception("添加第二层失败");
                }

                if (labelTwo.getLabelThrees() != null && labelTwo.getLabelThrees().size() > 0){
                    for (PrescriptionLabelThree labelThree : labelTwo.getLabelThrees()) {
                        labelThree.setLabelTwoId(labelTwo.getId());
                        insert = prescriptionLabelThreeDao.insert(labelThree);
                        if (insert <= 0){
                            throw new Exception("添加的第三层失败");
                        }
                    }
                }
            }
        }
        return insert;
    }
}